import React, { Component, PropTypes } from 'react';
import ItemTypes from '../PreviewTool/ItemTypes';
import { ajax } from 'utils/index';
import {initForm,modifyItem,saveItem} from '../../actions/index';
import { Button,Form,Input,Field,Dialog,Tab,Dropdown,Menu,Icon,Overlay,Badge,Select,Checkbox,Radio  } from 'qnui';
import { Row, Col } from 'qnui/lib/grid';
import ImageSelector from 'components/ImageSelector/index';


const FormItem = Form.Item;

export default class FormToolBase extends Component {
	constructor(props) {
		super(props);
		this.state = {
			showPicDialog:false,
			maxPic:1,
			aspectRatio:0,
			onlyCrop:false,
			picFieldName:"",
			dataSource:[]
		};
		['saveSelectedImage','onUploadError'].map(fn => {
            this[fn] = this[fn].bind(this);
        });
	}
	field = new Field(this);
	componentWillReceiveProps(nextProps) {
		let cards = nextProps.dataSource;
		let dataSource=[];
		if(cards[0].settingId>0){
			const card = cards.filter(c => c.id === cards[0].settingId)[0];
			if(card){
				for(let name in card.formData){
					this.field.setValue(name, card.formData[name]);
					if(card.formField[name] && card.formField[name].dataApi==""){
						dataSource[name]=JSON.parse(card.formField[name].dataSource);
					}
					if(card.formField[name] &&  card.formField[name].dataApi){
						let _self = this;
						ajax({
						  api: card.formField[name].dataApi,
						  method: 'GET',
						  data:{}
						},(json) => {
						   dataSource[name] = json.data;
						   _self.setState({dataSource});
						});
					}
				}
				this.setState({dataSource});
			}
		}
    }
	findCard(id) {
		let cards = this.props.dataSource;
		const card = cards.filter(c => c.id === id)[0];
		return {
		  card,
		  index: cards.indexOf(card)
		};
	}			
	onSubmit(e) {
		const values = this.field.getValues();
		const data = this.props.dataSource;
		const settingId = data[0].settingId;
		const {card,index} = this.findCard(settingId);
		const ordinal = [];
		data.map((da,key)=>{
			if(key>1){
			ordinal.push({compId:da.compId,ordinal:key,is_delete:da.isDelete,comp_code:da.code});
			}
		});
		this.props.dispatch(saveItem(index,ordinal,values,data[0].pageId));
	}
	saveSelectedImage(res){
		const picUrl = res.picture.picture_path;
		const pixel = res.picture.pixel;
		const data = this.props.dataSource;
		const {index} = this.findCard(data[0].settingId);
		this.field.setValue(this.state.picFieldName, picUrl);
		const values = this.field.getValues();
		this.props.dispatch(modifyItem(index,values));
		this.setState({showPicDialog:false});
	}
	onUploadError(err,res){
		Dialog.alert({content:"上传图片错误！请重试"});
	}
	showImageSelector(max,aspectRatio,onlyCrop,picFieldName){
		//每次调用时应清空图片选择器已选择的图片
		this.setState({"maxPic":max,"aspectRatio":aspectRatio,"onlyCrop":onlyCrop,showPicDialog:true,picFieldName})
	}
	setForm(){
		const init = this.field.init;
		const {card} = this.findCard(this.props.dataSource[0].settingId);
		// const data = this.props.dataSource;
		// const settingId = data[0].settingId;
		// let curdata = data.filter(c => c.id === settingId)[0];

		if(card!=null){
			const formField = card.formField;
			let formData = card.formData;
			var rows = [];
			for (var key in formField) {
				formField[key]["name"]=key;
				switch(formField[key].type){
					case "title":
						rows.push(<li key={key}><h3> {formField[key].title}</h3></li>);
					break;
					case "annotation":
						rows.push(<li key={formField.length+key}><h3> {formField[key].title}</h3></li>);
						rows.push(<li key={key}>{formField[key].placeholder}</li>);
					break;
					case "picture":
						const pic = "url("+formData[key]+"_290x290)";
						const picFieldName = formField[key].name;
						rows.push(<li key={formField.length+key}><h6>{formField[key].title}</h6></li>);
						rows.push(<li key={key}>
									<Input {...init(formField[key].name)}  htmlType="hidden" />
									<div onClick={this.showImageSelector.bind(this,formField[key].max,formField[key].aspectRatio,formField[key].onlyCrop=="true",picFieldName)} 
										 style={{cursor:"pointer",
												 padding:"43px",
												 backgroundImage:pic,
												 backgroundRepeat:"no-repeat",
												 backgroundColor:"#f0f0f0",
												 backgroundSize:"contain",
												 color:"#FFF",
												 fontSize:"24px",
												 textAlign:"center"}}>
										 <i className="tool-icon iconfont">&#xe60a;</i>
									</div>
								  </li>);
					break;
					case "text":
						const icon = formField[key].hasicon?<i style={{fontSize:"24px",cursor:"pointer",position: "absolute",right:"1px",top: "1px",color:"#C7C7C7",background:"#f0f0f0",padding:"0 5px"}} className="tool-icon iconfont" >&#xe617;</i>:"";
						rows.push(
							<li key={key}><h6>{formField[key].title}</h6>
								<FormItem style={{position:"relative"}} required={false} size="large">
									<Input {...init(formField[key].name)} placeholder={formField[key].placeholder} />
									{icon}
								</FormItem>
							</li>
						);
					break;
					case "select":
						//const dataSource = this.props.component.data[settingId];
						
						rows.push(
							<li key={key}><h3>{formField[key].title}</h3>
								<Select {...init(formField[key].name)}  dataSource={this.state.dataSource[formField[key].name]}/>
							</li>
						);
						
					break;
					
					case "checkbox":
						rows.push(
							<li key={key}><h3>{formField[key].title}</h3>
							<Checkbox.Group {...init(formField[key].name)} dataSource={this.state.dataSource[formField[key].name]}  />
							</li>
						);
						
					break;
					case "radio":
						rows.push(
							<li key={key}><h3>{formField[key].title}</h3>
							<Radio.Group {...init(formField[key].name)} dataSource={this.state.dataSource[formField[key].name]}  />
							</li>
						);
						
					break;
					
				}
			}
			return <div>{rows}</div>;
		}else{
			return <div />;
		}
	}
	render() {
		//console.log(this.state);
		return (
		    <Form id="myForm" field={this.field} size="large" style={{width:"100%"}}>
				<div style={{padding:"0 10px",position:"relative",overflowX:"hidden", overflowY: "auto",height:this.props.height}}>
					<ul>
					{this.setForm()}
					</ul>
				</div>
				<div style={{textAlign:"center",position:"absolute",bottom:"20px",width:"100%"}}>
					<Button size="large" type="normal" >取消</Button> &nbsp;&nbsp;
					<Button onClick={this.onSubmit.bind(this)} style={{marginLeft:"20px"}} size="large" type="secondary" >保存</Button>
				</div>
				<ImageSelector 
					maxPic={this.state.maxPic}
					minPicSize={{"width":40,"height":40}}
					showPicDialog={this.state.showPicDialog}
					onClose={()=>{this.setState({"showPicDialog":false})}}
					onUploadSuccess={this.saveSelectedImage}
					onUploadError={this.onUploadError}
					defaultPicType="upload"
					selectorStyle={{"width":"1100px"}}
					aspectRatio={this.state.aspectRatio}
					onlyCrop={this.state.onlyCrop}
					cropperDialogStyle={{"width":"1000px"}}
					copperStyle={{"height":"420px"}}
					uploadServer={window.img_upload_server}
					previewList={["300x168"]}
					userNick={window.info.user_nick}
					pageSize={32}
					>
				</ImageSelector>
			</Form>
		);
	}
}
